import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectDemo {
    public static void main(String[] args) {
        SelectDemo.select();
    }

    private static void select() {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // 1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取数据库链接、
            String url = "jdbc:mysql://localhost:3306/jdbctest?zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai";
            con = DriverManager.getConnection(url, "root", "root");
            // 3.1sql语句
            String sql = "select * from user where username = '小舞'";
            // 3.2执行sql语句的对象
            pstmt = con.prepareStatement(sql);
            // 3.3执行sql
            rs = pstmt.executeQuery();
            // 4.解析结果集
            while (rs.next()) {
                System.out.print(rs.getInt("id") + " ");
                System.out.print(rs.getString("username")+ " ");
                System.out.print(rs.getString("password")+ " ");
                System.out.print(rs.getInt("age") + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5.关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                rs = null;
            }
            if(pstmt != null){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                pstmt = null;
            }
            if(con != null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
}
